package cn.zhiquxing.send;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.zhiquxing.common.constants.MyMsgConstant;
import cn.zhiquxing.domain.BasicResultVO;
import cn.zhiquxing.domain.MessageParam;
import cn.zhiquxing.domain.ProcessContext;
import cn.zhiquxing.domain.SendTaskModel;
import cn.zhiquxing.enums.RespStatusEnum;
import cn.zhiquxing.pipeline.BusinessProcess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 发送消息前置校验
 */
@Slf4j
@Service
public class SendPreCheckAction implements BusinessProcess<SendTaskModel> {
    @Override
    public void process(ProcessContext<SendTaskModel> context) {
        SendTaskModel processModel = context.getProcessModel();

        Long messageTemplateId = processModel.getMessageTemplateId();
        List<MessageParam> messageParamList = processModel.getMessageParamList();
        if (Objects.isNull(messageParamList) || CollUtil.isEmpty(messageParamList)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS, "模板id或参数列表不能为空"));
            return;
        }

        List<MessageParam> resultMessageParamList = messageParamList.stream().filter(messageParam -> 
                StrUtil.isBlank(messageParam.getReceiver())).collect(Collectors.toList());
        if (CollUtil.isEmpty(resultMessageParamList)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.CLIENT_BAD_PARAMETERS, "含接受者的参数列表为空"));
            return;
        }

        if (resultMessageParamList.stream().anyMatch(messageParam -> 
                messageParam.getReceiver().split(StrPool.COMMA).length > MyMsgConstant.BATCH_RECEIVER_SIZE)) {
            context.setNeedBreak(true).setResponse(BasicResultVO.fail(RespStatusEnum.TOO_MANY_RECEIVER));
            return;
        }

        processModel.setMessageParamList(resultMessageParamList);
    }
}
